import os
from datetime import datetime

def tree(directory, indent='', file=None):
    files = os.listdir(directory)
    for file_name in files:
        path = os.path.join(directory, file_name)
        if os.path.isdir(path):
            file.write(indent + '|-- ' + file_name + '\n')
            tree(path, indent + '|   ', file)
        else:
            file.write(indent + '|-- ' + file_name + '\n')

try:
    # 获取当前时间
    current_time = datetime.now().strftime('%Y%m%d%H%M%S')
    # 输入要查询的路径
    path = input("请输入要查询的路径，按回车键确认：")
    # 检查路径是否存在
    if not os.path.exists(path):
        raise FileNotFoundError("系统找不到指定的路径: " + path)
    # 创建并打开一个txt文件，文件名包含当前时间和目录路径
    file_name = current_time + '_path.txt'
    with open(file_name, 'w', encoding='utf-8') as file:
        # 调用tree函数，并将文件对象传递给它
        tree(path, file=file)
        print("文件生成成功！文件名为：" + file_name)
except KeyboardInterrupt:
    print("输入错误！")
except FileNotFoundError as e:
    print(str(e))
except OSError:
    print("文件名、目录名或卷标语法不正确。")
